﻿using NhWeather.Modbus;
using NhWeather.nModbusDevice;
using NhWeather.Properties;
using NhWeather.Register;
using NhWeather.Service;
using System;
using System.Collections.ObjectModel;
using System.IO.Ports;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace NhWeather;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public static MainWindow Instance { get; private set; }
    private readonly SettingsViewModel SettingsViewModel = new();

    public MainWindow()
    {
        InitializeComponent();

        Instance = this;
        DataContext = SettingsViewModel;
        Cb串口选择_DropDownOpened(Instance, new RoutedEventArgs());
    }

    private void Bt打开串口_Click(object sender, RoutedEventArgs e)
    {
        var cs = CommunicationService.Instance;
        if (bt打开串口.Content.ToString() == "打开串口")
        {
            cs.Spio.握手帧 = Tb握手帧.Text;
            if (cs.Spio.Open(cb串口选择.Text))
            {
                bt打开串口.Content = "关闭串口";
                bt打开串口.Foreground = Brushes.Green;
            }
        }
        else
        {
            cs.Spio.Close();
            bt打开串口.Content = "打开串口";
            bt打开串口.Foreground = Brushes.Red;
        }
    }

    private void Cb串口选择_DropDownOpened(object sender, EventArgs e)
    {
        string[] vs = SerialPort.GetPortNames();
        Array.Sort(vs, new FilesNameComparer());
        cb串口选择.ItemsSource = vs;
    }

    private void Button添加虚拟设备_Click(object sender, RoutedEventArgs e)
    {
        var controlDevcie = new ControlDevcie();
        controlDevcie.InitializeRegisters(Settings.Default.IsDefaultRecorder);
        DeviceContainer.Children.Add(controlDevcie);
    }

    private void Window_Closed(object sender, EventArgs e)
    {
        WeatherData.IsRun = false;
        Environment.Exit(0);
    }

    private void MenuItem_Exit_Click(object sender, RoutedEventArgs e)
    {
        Application.Current.Shutdown();
    }
}

